package xyz.jangle.service.impl;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.multipart.MultipartFile;

import xyz.jangle.dao.BsAttachmentMapper;
import xyz.jangle.model.BsAttachment;
import xyz.jangle.model.BsFileBit;
import xyz.jangle.service.BsAttachmentService;
import xyz.jangle.service.BsFileBitService;
import xyz.jangle.utils.JConstant;

@Service
public class BsAttachmentServiceImpl implements BsAttachmentService {
	
	@Autowired
	private BsAttachmentMapper bsAttachmentMapper;
	@Autowired
	private BsFileBitService bsFileBitService;
	@Autowired
	private DataSourceTransactionManager txManager;
	protected Logger logger = Logger.getLogger(getClass());

	@Override
	public Map<String, Object> selectPage(BsAttachment bsAttachment) {
		Map<String, Object> map = new HashMap<String, Object>();
		List<BsAttachment> list = bsAttachmentMapper.selectPage(bsAttachment);
//		Long count = bsAttachmentMapper.selectPageCount(bsAttachment);
		map.put("list", list);
		map.put("code", JConstant.SUCCESS_CODE);
//		map.put("count", count);
		return map;
	}

	@Override
	public Map<String, Object> selectByPrimaryKey(BsAttachment record) {
		Map<String, Object> map = new HashMap<String, Object>();
		BsAttachment bsAttachment = bsAttachmentMapper.selectByPrimaryKey(record.getId());
		map.put("model", bsAttachment);
		map.put("code", JConstant.SUCCESS_CODE);
		return map;
	}

	@Override
	public Map<String, Object> insertOrUpdate(BsAttachment record) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(record.getId() == null) {
			bsAttachmentMapper.insert(record);
		}else {
			bsAttachmentMapper.updateByPrimaryKey(record);
		}
		map.put("model", record);
		map.put("code", JConstant.SUCCESS_CODE);
		map.put("message", JConstant.SUCCESS_MESSAGE);
		return map;
	}

	@Override
	public Map<String, Object> batchDeleteByPrimaryKey(BsAttachment record) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(record.getIds()!=null) {
			record.setIdsArray(record.getIds().split(","));
		}else {
			record.setIdsArray(new String[0]);
		}
		bsAttachmentMapper.batchDeleteByPrimaryKey(record);
		map.put("model", record);
		map.put("code", JConstant.SUCCESS_CODE);
		map.put("message", JConstant.SUCCESS_MESSAGE);
		return map;
	}

	@Override
	public Map<String, Object> deleteByPrimaryKey(BsAttachment record) {
		Map<String, Object> map = new HashMap<String, Object>();
		bsAttachmentMapper.deleteByPrimaryKey(record.getId());
		map.put("model", record);
		map.put("code", JConstant.SUCCESS_CODE);
		map.put("message", JConstant.SUCCESS_MESSAGE);
		return map;
	}
	
	@Override
	public Map<String, Object> downLoadById(BsAttachment record, HttpServletResponse response) {
		BsAttachment attachment = bsAttachmentMapper.selectByPrimaryKey(record.getId());
		BsFileBit fileBit = new BsFileBit();
		fileBit.setId(attachment.getAttId());
		Map<String, Object> map = bsFileBitService.selectByPrimaryKey(fileBit);
		if (map.get("model") == null) {
			logger.error("下载时未找到文件实体");
			return null;
		}
		byte[] bitContent = ((BsFileBit) map.get("model")).getBitContent();
		response.setCharacterEncoding("UTF-8");
		response.setContentType("multipart/form-data");
		String fileName = attachment.getAttName();
		try {
//			fileName = java.net.URLEncoder.encode(attachment.getAttName(),"UTF-8");
			fileName = new String(attachment.getAttName().getBytes("UTF-8"), "ISO8859-1");
		} catch (UnsupportedEncodingException e1) {
			logger.error("附件文件名转换时异常", e1);
		}
//		logger.error(fileName);
		response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
		try {
			BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
			bufferedOutputStream.write(bitContent);
			bufferedOutputStream.flush();
			bufferedOutputStream.close();
		} catch (IOException e) {
			logger.error("文件下载时异常", e);
		}
//		attachment.setDmDesc((String) httpSession.getAttribute(JConstant.ip));
//		attachment.setAttExtends2((String) httpSession.getAttribute(JConstant.city));
//		if (bsDictService.noRecordForMyIp(attachment.getDmDesc())) {
//			return null;
//		}
//		bsMailService.insertOrUpdate(attachment);
		return null;
	}

	@Override
	public Map<String, Object> uploadBatch(MultipartFile[] files, BsAttachment record) {
		if (files == null) {
			logger.error("未获取到附件");
			return new HashMap<String, Object>();
		}
		//事务的开始
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = txManager.getTransaction(def);
		try {
			for (int i = 0; i < files.length; i++) {
				if (!files[i].isEmpty()) {
					String originalname = files[i].getOriginalFilename();
//					System.out.println(originalname);
					record.setAttName(originalname); //设置文件名
					// TODO 添加扩展名和文件大小的逻辑
					// writeToLocal(files[i]); // TODO将文件写入，可改为写入数据库，或文件服务器。
					BsFileBit bsFileBit = new BsFileBit();
					bsFileBit.setBitContent(files[i].getBytes());
					bsFileBitService.insert(bsFileBit);
					record.setAttId(bsFileBit.getId());
					record.setId(null);
					record.setStatus(1);
					this.insertOrUpdate(record);
				} else {
					logger.info("files is empty");
				}
			}
		} catch (IOException e) {
			logger.error("文件写入时异常", e);
			txManager.rollback(status);//回滚事务
			return new HashMap<String, Object>();
			// 做相应的异常信息返回
		}
		txManager.commit(status);//提交事务
		return new HashMap<String, Object>();
	}
	
	
	

}
